# -*- encoding: utf-8 -*-
# jupiter 2003 parser
############################################################################
#    Copyright (C) 2007 by Håvard Gulldahl                                 #
#    havard@gulldahl.no                                                    #
#                                                                          #
#    This program is free software; you can redistribute it and#or modify  #
#    it under the terms of the GNU General Public License as published by  #
#    the Free Software Foundation; either version 2 of the License, or     #
#    (at your option) any later version.                                   #
#                                                                          #
#    This program is distributed in the hope that it will be useful,       #
#    but WITHOUT ANY WARRANTY; without even the implied warranty of        #
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         #
#    GNU General Public License for more details.                          #
#                                                                          #
#    You should have received a copy of the GNU General Public License     #
#    along with this program; if not, write to the                         #
#    Free Software Foundation, Inc.,                                       #
#    59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             #
############################################################################

import logging, re
from datetime import datetime
from time import strptime
from cgi import parse_qs
import BeautifulSoup
import jeje.parser

class parser(jeje.parser.ejeje_parser):
    def parse_enkeltjournal(self, suppe, uri):
        #jeje.parser.ejeje_parser.__init__(self, suppe, postjournal_samling)
        logging.info('starter jupiter 2003-parser')
        dato = suppe.h1.string[len('Dagens postjournal '):]
        logging.debug('fant dato %s', dato)
        self.sett_info(dato)
        logging.debug('finner tittelposter i suppa')
        _journaltabell = suppe.find('table', 'mx')
        try:
            _tittelposter = _journaltabell.findAllChildren(recursive=False)[1:]
        except TypeError: # BeautifulSoup 3.0.4 changed the name of the method
            _tittelposter = _journaltabell.findChildren(recursive=False)[1:]
        logging.debug('fant %d titler', len(_tittelposter))
        for i, tp in enumerate(_tittelposter):


            #<td class="mxheader">Dok.dato</td>
            #<td class="mxheader">Type</td>
            #<td class="mxheader">Grad.<br>U.off.</td>
            #<td class="mxheader">Beskrivelse</td>
            #<td class="mxheader">Avsender/ Mottaker</td>
            #<td class="mxheader">Saksb.</td>
            #<td class="mxheader">Saksnummer</td>
            #<td class="mxheader">L&oslash;penr.</td>
            #<td class="mxheader">Dok</td>

            _dokumentdato, _type, _grad, _tittel, _adressat, _saksbehandler, \
            _arkivsaksnr, _refnr, _uri = [b.contents for b in tp.findAll('td', 'mxcell')]
            logging.debug('arbeider med post #%d: %s', i+1, self.trekk_sammen_streng(_tittel))

            post = self.legg_til_post()
            post.sett_tittel(self.trekk_sammen_streng(_tittel))
            #post.sett_offentlig(-1 != tp.a.find('/k2000/k2post.sett_nsf/viewAttachmentsMail'))
            arkivsaksnr, dokumentnr = self.trekk_sammen_streng(_arkivsaksnr).split('-')
            #logging.debug('arkivsaksnr: %s, refnr: %s', arkivsaksnr, _refnr)
            post.sett_arkivsaksnr(arkivsaksnr)
            post.sett_dokumentnr(dokumentnr)
            post.sett_refnr(self.trekk_sammen_streng(_refnr))
            post.sett_adressat(self.trekk_sammen_streng(_adressat))
            person = post.sett_saksbehandler(unicode(_saksbehandler[0].string))
            person.uri = unicode(_saksbehandler[0]['href'])
            #logging.debug('dokumentdato: %s', self.trekk_sammen_streng(_dokumentdato))
            post.sett_dokumentdato(datetime(*strptime(self.trekk_sammen_streng(_dokumentdato), '%d-%m-%y')[0:6]))
            try:
                post.sett_lovreferanse(parse_qs(_grad[0]['href'].split('?')[1])['cmd'][0].replace('paragraf', '').strip())
                post.sett_offentlig(False)
            except TypeError:
                pass 
            post.sett_retning(_type[0])
            if isinstance(_uri[0], BeautifulSoup.Tag):
                post.sett_dok_uri(self.absoluttifiser(unicode(_uri[0]['href']), uri))
            post.kontroller_felter()
        return self.journalposter
